package com.zhiwei.msf.common.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.zhiwei.msf.common.constant.HttpConstants;
import com.zhiwei.msf.common.constant.ResultResponseMsg;
import com.zhiwei.msf.common.service.GatewayService;

import lombok.extern.slf4j.Slf4j;

/**
 * @function 网关服务实现类
 * @author zhiwei.yang
 * @time 2020-2-28-10:23
 */
@Slf4j
public class GatewayProxyServiceImpl implements GatewayService {

	/**
	 * 网关服务名
	 **/
	private final String GATEWAY_SERVICE_NAME = "publish-gateway";
	private final String GATEWAY_SERVICE_API = "http://" + GATEWAY_SERVICE_NAME + "/publish-gateway/gateway";

	// 生产黄金Redis缓存
	private final Set<String> cacheWhiteSet = new ConcurrentSkipListSet<>();

	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private PathMatcher pathMatcher;

	@Override
	public String checkToken(String token) {
		Map<String, String> requestMap = new HashMap<>();
		requestMap.put(HttpConstants.HEADER_TOKEN, token);
		String url = GATEWAY_SERVICE_API + "/token/check?token={token}";
		ResultResponseMsg resultResponseMsg = restTemplate.getForEntity(url, ResultResponseMsg.class, requestMap)
				.getBody();
		return (String) resultResponseMsg.getData();
	}

	@Override
	public List<String> syncWhiteUrlList() {
		String url = GATEWAY_SERVICE_API + "/whiteList";
		ResultResponseMsg resultResponseMsg = restTemplate.getForEntity(url, ResultResponseMsg.class).getBody();
		List<String> whiteList = JSON.parseArray(JSON.toJSONString(resultResponseMsg.getData()), String.class);
		cacheWhiteSet.addAll(whiteList);
		log.info("白名单地址：{}", whiteList);
		return whiteList;
	}

	@Override
	public synchronized boolean checkWhiteUrl(String requestUri) {
		if (CollectionUtils.isEmpty(cacheWhiteSet)) {
			syncWhiteUrlList();
		}
		for (String path : cacheWhiteSet) {
			if (pathMatcher.match(path, requestUri)) {
				return true;
			}
		}
		return false;
	}
}